﻿CREATE TRIGGER [tr_Menu_Insert_TabIndex]
ON [dbo].[t_Menu]
FOR INSERT,UPDATE
AS

IF NOT UPDATE(TabIndex) RETURN
DECLARE @Base sysname SET @Base = 'tr_Menu_'
DECLARE @LevelInsert varchar SET @LevelInsert = TRIGGER_NESTLEVEL(Object_ID(@Base+'Insert_TabIndex'))
DECLARE @LevelDelete varchar SET @LevelDelete = TRIGGER_NESTLEVEL(Object_ID(@Base+'Delete_TabIndex'))

IF (@LevelInsert > 1) OR (@LevelDelete > 0)	RETURN

PRINT object_name(@@PROCID)+':'+@LevelDelete

DECLARE @TabIndex int,@TabIndexPrev int,@MenuID int,@ParentID int
SELECT @TabIndex = i.TabIndex, @MenuID = i.MenuID,
			 @ParentID = i.ParentMenuID,@TabIndexPrev = d.TabIndex
FROM inserted i LEFT OUTER JOIN deleted d ON i.MenuID = d.MenuID

IF @TabIndex > @TabIndexPrev-- it's being moved down
	UPDATE t_Menu SET TabIndex = @TabIndex+2 FROM t_Menu WHERE MenuID = @MenuID

UPDATE t_Menu SET TabIndex = TabIndex + 1 WHERE ParentMenuID = @ParentID AND TabIndex >= @TabIndex AND MenuID <> @MenuID

EXEC sp__menu_RePaginate @ParentID
